import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/lib_basemodel/user/user.dart';
import 'package:gameplay_flutter/lib_baseview/widget/web/common_web_view.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_text.dart';
import 'package:gameplay_flutter/m_me/constants/dialog_manager.dart';
import 'package:gameplay_flutter/m_me/constants/me_assets_constants.dart';
import 'package:gameplay_flutter/m_me/constants/me_h5_url.dart';
import 'package:gameplay_flutter/m_me/me_controller.dart';
import 'package:gameplay_flutter/m_me/me_followers/me_followers_page.dart';
import 'package:gameplay_flutter/m_me/me_page/me_page_controller.dart';
import 'package:gameplay_flutter/m_me/me_setting_page/me_getting_page.dart';
import 'package:gameplay_flutter/m_me/model/me_menu_item.dart';
import 'package:gameplay_flutter/m_me/user_deit_page/user_edit_page.dart';
import 'package:gameplay_flutter/m_me/user_details_page/user_details_page.dart';
import 'package:gameplay_flutter/resource/language/generated/l10n.dart';
import 'package:get/get.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:ones/ui.dart';
import '../../lib_baseview/utils/cache_util.dart';
import '../../m_main/debug/debug_page.dart';
import '../in_app_purchase_service.dart';
import '../me_followers/me_history_page.dart';
import '../me_followers/me_visitors_page.dart';

class MePageNew extends StatefulWidget {
  const MePageNew({super.key});

  @override
  _MePageNewState createState() => _MePageNewState();
}

class _MePageNewState extends State<MePageNew>
    with WidgetsBindingObserver, RouteAware {
  late final MePageController mePageController;
  late final MeController meController;
  late final RouteObserver<PageRoute> routeObserver;

  // 添加状态变量来控制余额的可见性
  bool _isBalanceVisible = false;

  // 获取全局内购服务的单例
  final InAppPurchaseService _purchaseService = InAppPurchaseService();

  @override
  void initState() {
    super.initState();
    // 确保在Get.find之前完成注册
    Get.lazyPut<RouteObserver<PageRoute<dynamic>>>(() => RouteObserver());
    routeObserver = Get.find<RouteObserver<PageRoute>>();
    meController = Get.put(MeController());
    mePageController = Get.put(MePageController());

    // 首次加载数据
    _loadData();

    // 添加生命周期观察者
    WidgetsBinding.instance.addObserver(this);

    // 监听 languageCode 的变化
    ever(meController.languageCode, (code) {
      _onLocaleChange();
    });
    _initializeInAppPurchase();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 注册路由观察
    final route = ModalRoute.of(context);
    if (route is PageRoute) {
      routeObserver.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    // 移除观察者
    WidgetsBinding.instance.removeObserver(this);
    routeObserver.unsubscribe(this);
    _purchaseService.dispose();
    meController.dispose();
    mePageController.dispose();
    super.dispose();
  }

  // 应用生命周期变化回调
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // _loadData();
    }
  }

  // 路由出现时回调（包括首次进入和从其他页面返回）
  @override
  void didPushNext() {
    // _loadData();
  }

  // 其他页面弹出当前页面显示时回调
  @override
  void didPopNext() {
    // _loadData();
  }

  _loadData() {
    meController.getUserMine();
  }

  void _onLocaleChange() {
    // 刷新数据
    mePageController.getMeUIData();
  }

  // 内购初始化方法，例如预先查询商品列表（根据你的业务需求可以扩展）
  void _initializeInAppPurchase() async {
    final bool available = await InAppPurchase.instance.isAvailable();
    if (available) {
      debugPrint('内购服务已就绪');
    } else {
      debugPrint('内购服务不可用');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFAFAFA),
      floatingActionButton: FloatingActionButton(
        heroTag: "MePageNew",
        onPressed: () {
          DebugPage.show(context);
        },
        child: const Icon(Icons.language), // 示例图标
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endTop,
      body: Stack(
        children: [
          Container(
            height: 143.h,
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFFDCD4FF), Color(0x00FFFFFF)],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
          ),
          SafeArea(
              child: SingleChildScrollView(
            child: Obx(
              () => Column(
                children: [
                  _userBaseData(context, meController.user.value),
                  _count(context, meController.user.value),
                  _recharge(context, meController.user.value),
                  _setting(context, mePageController.meMenu.value.subMenuList,
                      mePageController.meMenu.value.baseMenuList),
                ],
              ),
            ),
          )),
        ],
      ),
    );
  }

  Widget _userBaseData(BuildContext context, User? user) {
    return Container(
      padding: EdgeInsetsDirectional.only(top: 67.h, start: 15.w, end: 15.w),
      child: Row(
        children: [
          // 头像部分
          Stack(
            children: [
              CircleAvatar(
                backgroundColor: Color(0xFFFFFFFF),
                radius: 37.r,
                backgroundImage:
                    CachedNetworkImageProvider(user?.headPortraitsUrl ?? ''),
                // 使用 NetworkImage
                child: user?.headPortraitsUrl == null
                    ? Image.asset(MeAssetsConstants.iconEmpty) // 如果没有图片，显示加载动画
                    : null,
              ),
              Padding(
                padding: EdgeInsetsDirectional.only(top: 49.h, start: 47.w),
                child: Image.asset(
                  MeAssetsConstants.iconHome,
                  width: 25.w,
                  height: 25.h,
                  fit: BoxFit.cover,
                ),
              ),
            ],
          ).onClick(() {
            Get.to(() => const UserDetailsPage());
          }),

          SizedBox(width: 14.w),

          // 用户信息部分
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 名称和等级
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    (user?.nickname ?? 'Name').text(
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        color: const Color(0xFF000000),
                        fontSize: 20.sp,
                        weight: TextFontWeight.medium),
                    SizedBox(width: 1.w),
                    Container(
                      height: 14.h,
                      padding: EdgeInsetsDirectional.symmetric(
                        horizontal: 8.w,
                      ),
                      decoration: BoxDecoration(
                        color: const Color(0xFF9ED1FF),
                        borderRadius: BorderRadius.circular(7.r),
                      ),
                      child: Text(
                        'LV${(user?.memberLevel ?? 0).toString()}',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 10.sp,
                          decoration: TextDecoration.none,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 3.h),
                // ID信息
                Row(
                  children: [
                    'ID: ${user?.userCode ?? ''}'.text(
                        color: Color(0xFFC1C1C1),
                        fontSize: 14.sp,
                        weight: TextFontWeight.regular),
                    SizedBox(width: 4.w),
                    Image.asset(
                      MeAssetsConstants.iconCopyID,
                      width: 20.w,
                      height: 20.h,
                      fit: BoxFit.cover,
                    ).onClick(() {
                      Clipboard.setData(
                          ClipboardData(text: user?.userCode ?? ''));
                      _copyToClipboard(user?.userCode ?? '');
                    })
                  ],
                ),
                SizedBox(height: 4.h),
                // 个性签名
                (user?.about ?? T.current.me1_signature).text(
                  color: const Color(0xFFC1C1C1),
                  fontSize: 11.sp,
                  weight: TextFontWeight.regular,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              ],
            ),
          ),

          // 编辑按钮
          Container(
            margin: EdgeInsetsDirectional.only(start: 8.w),
            height: 29.h,
            child: ElevatedButton(
              onPressed: () {
                Get.to(const UserEditPage());
              },
              child: T.current.me_edit.text(
                  color: Colors.white,
                  fontSize: 16.sp,
                  weight: TextFontWeight.regular),
              style: ElevatedButton.styleFrom(
                padding: EdgeInsetsDirectional.zero,
                backgroundColor: Colors.transparent,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.r),
                ),
                shadowColor: Colors.transparent,
              ),
            ),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color(0xFF8A72FE),
                  Color(0xFF6549EC),
                ],
              ),
              borderRadius: BorderRadius.circular(25.r),
            ),
          ),
        ],
      ),
    );
  }

  String _getAttentions(dynamic attentions) {
    if (attentions is String) {
      return attentions;
    } else if (attentions is int) {
      return attentions.toString();
    } else {
      return '0';
    }
  }

  Widget _count(BuildContext context, User? user) {
    return Container(
      padding: EdgeInsetsDirectional.only(top: 22.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _countStatItem(
              (user?.accessCount ?? 0).toString(), T.current.me_visitors, 0),
          _countStatItem(
              _getAttentions(user?.attentions), T.current.me_following, 1),
          _countStatItem(
              (user?.fans ?? 0).toString(), T.current.me_followers, 2),
          _countStatItem(
              (user?.totalFootprints ?? 0).toString(), T.current.me_history, 3),
        ],
      ),
    );
  }

  Widget _countStatItem(String count, String label, int type) {
    return Column(
      children: [
        count.text(
          color: const Color(0xFF000000),
          fontSize: 18.sp,
          weight: TextFontWeight.regular,
        ),
        SizedBox(height: 4.h),
        label.text(
          fontSize: 12.sp,
          color: const Color(0xFFC1C1C1),
          weight: TextFontWeight.regular,
        ),
      ],
    ).onClick(() {
      switch (type) {
        case 0:
          Get.to(() => const MeVisitorsPage());
        case 1:
          Get.to(() => MeFollowersPage(type: type));
        case 2:
          Get.to(() => MeFollowersPage(type: type));
        case 3:
          Get.to(() => const MeHistoryPage());
      }
    });
  }

  Widget _recharge(BuildContext context, User? user) {
    String iconWealth = MeAssetsConstants.getIconWealth(context);
    String iconDressUp = MeAssetsConstants.getIconDressUp(context);
    String iconRechargeArrow =
        MeAssetsConstants.getIconMeRechargeArrow1(context);
    String iconRechargeArrow0 =
        MeAssetsConstants.getIconMeRechargeArrow0(context);

    // 根据 _isBalanceVisible 状态来决定显示余额还是 *****
    String balanceText =
        _isBalanceVisible ? (user?.virtualBalance ?? 0).toString() : '****';

    return Container(
        margin: EdgeInsetsDirectional.only(top: 28.h, start: 15.w, end: 15.w),
        decoration: BoxDecoration(
          color: Color(0xFFFFFFFF),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Padding(
          padding:
              EdgeInsetsDirectional.only(top: 10.h, start: 12.w, bottom: 15.w),
          child: Column(
            children: [
              Padding(
                padding: EdgeInsetsDirectional.only(end: 20.w),
                child: Row(
                  children: [
                    T.current.c_recharge.text(
                      fontSize: 18.sp,
                      color: const Color(0xFF000000),
                      weight: TextFontWeight.regular,
                    ),
                    SizedBox(
                      width: 4.w,
                    ),
                    Image.asset(
                      MeAssetsConstants.getIconBalanceVisibility(
                          _isBalanceVisible),
                      width: 26.w,
                      height: 26.h,
                      fit: BoxFit.cover,
                    ).onClick(() {
                      setState(() {
                        _isBalanceVisible = !_isBalanceVisible;
                      });
                    }),
                    const Spacer(),
                    Row(
                      children: [
                        Image.asset(
                          MeAssetsConstants.iconGold,
                          width: 15.w,
                          height: 15.h,
                          fit: BoxFit.cover,
                        ),
                        SizedBox(
                          width: 4.w,
                        ),
                        balanceText.text(
                          fontSize: 14.sp,
                          color: const Color(0xFF000000),
                          weight: TextFontWeight.regular,
                        ),
                        SizedBox(
                          width: 3.w,
                        ),
                        Image.asset(
                          iconRechargeArrow0,
                          width: 14.w,
                          height: 14.h,
                          fit: BoxFit.cover,
                        ),
                      ],
                    ).onClick(() {
                      CommonWebView.show(context, MeH5UrlConstants.myWallet);
                    }),
                  ],
                ),
              ),
              SizedBox(
                height: 7.h,
              ),
              Padding(
                padding: EdgeInsetsDirectional.only(end: 25.w),
                child: Row(children: [
                  Container(
                      width: 149.w,
                      height: 71.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                        image: AssetImage(iconWealth),
                        fit: BoxFit.cover,
                      )),
                      child: Padding(
                        padding:
                            EdgeInsetsDirectional.only(top: 12.h, start: 9.w),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            T.current.me3_my_wellet.text(
                              fontSize: 14.sp,
                              color: const Color(0xFF000000),
                              weight: TextFontWeight.regular,
                            ),
                            SizedBox(
                              height: 4.h,
                            ),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                T.current.me1_join_now.text(
                                  fontSize: 10.sp,
                                  color: const Color(0xFFD8B500),
                                  weight: TextFontWeight.regular,
                                ),
                                Image.asset(
                                  iconRechargeArrow,
                                  width: 8.w,
                                  height: 8.h,
                                )
                              ],
                            ),
                          ],
                        ),
                      )).onClick(() {
                    CommonWebView.show(context, MeH5UrlConstants.myWallet);
                  }),
                  Spacer(),
                  Container(
                      width: 149.w,
                      height: 71.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                        image: AssetImage(iconDressUp),
                        fit: BoxFit.cover,
                      )),
                      child: Padding(
                        padding:
                            EdgeInsetsDirectional.only(top: 12.h, start: 9.w),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            T.current.me_dress_up_shop.text(
                              fontSize: 14.sp,
                              color: const Color(0xFF000000),
                              weight: TextFontWeight.regular,
                            ),
                            SizedBox(
                              height: 4.h,
                            ),
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Text(T.current.me1_join_now,
                                    style: TextStyle(
                                        fontSize: 10.sp,
                                        color: Color(0xFFD8B500),
                                        fontWeight: FontWeight.normal,
                                        decoration: TextDecoration.none)),
                                Image.asset(
                                  iconRechargeArrow,
                                  width: 8.w,
                                  height: 8.w,
                                )
                              ],
                            ),
                          ],
                        ),
                      )).onClick(() {
                    CommonWebView.show(context, MeH5UrlConstants.dressUpShop);
                  }),
                ]),
              ),
            ],
          ),
        ));
  }

  Widget _generalTools(BuildContext context, List<MeMenuItem> list) {
    return Container(
      margin: EdgeInsetsDirectional.only(top: 8.h, start: 15.w, end: 15.w),
      decoration: BoxDecoration(
        color: const Color(0xFFFFFFFF),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        SizedBox(
          height: 11.h,
        ),
        Padding(
            padding: EdgeInsetsDirectional.only(start: 12.w),
            child: Text(
              T.current.me_general_tools,
              style: TextStyle(
                  fontSize: 18.sp,
                  color: Color(0xFF000000),
                  fontWeight: FontWeight.normal,
                  decoration: TextDecoration.none),
            )),
        SizedBox(
          height: 12.h,
        ),
        GridView.count(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisCount: 4,
            children: List.generate(list.length, (index) {
              return InkWell(
                onTap: () {
                  if (list[index].routerMap != null &&
                      list[index].routerMap!.startsWith('http')) {
                    CommonWebView.show(
                      context,
                      list[index].routerMap ?? "",
                    );
                  } else {
                    // 显示 SnackBar 提示用户
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('No valid URL to open'),
                        duration: const Duration(seconds: 2),
                      ),
                    );
                  }
                },
                child: Column(children: [
                  Image.network(
                    list[index].icon ?? "",
                    width: 56.w,
                    height: 52.h,
                    fit: BoxFit.cover,
                  ),
                  SizedBox(
                    height: 4.h,
                  ),
                  Text(
                    list[index].name ?? "",
                    style: TextStyle(
                        fontSize: 10.sp,
                        color: Color(0xFF000000),
                        fontWeight: FontWeight.normal,
                        decoration: TextDecoration.none),
                  )
                ]),
              );
            }))
      ]),
    );
  }

  Widget _setting(BuildContext context, List<MeMenuItem> subMenuList,
      List<MeMenuItem> baseMenuList) {
    return Container(
        padding: EdgeInsetsDirectional.only(top: 10.h, bottom: 5.h),
        margin: EdgeInsetsDirectional.only(
            top: 8.h, start: 15.w, end: 15.w, bottom: 66.h),
        decoration: BoxDecoration(
          color: Color(0xFFFFFFFF),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Padding(
            padding: EdgeInsetsDirectional.only(start: 16.w),
            child: T.current.me_general_tools.text(
              fontSize: 18.sp,
              color: const Color(0xFF000000),
              weight: TextFontWeight.regular,
            ),
          ),
          SizedBox(
            height: 6.h,
          ),
          Column(
            children: List.generate(subMenuList.length, (index) {
              return _settingItem(context, subMenuList[index]);
            }),
          ),
          Padding(
            padding: EdgeInsetsDirectional.symmetric(vertical: 3.h),
            child: Divider(
              height: 0.5.h,
              // 使用ScreenUtil的h方法来设置高度
              thickness: 0.5.h,
              // 设置横线的厚度
              color: const Color(0xFFD8D8D8),
              // 设置横线的颜色
              indent: 18.w,
              // 设置横线左边的缩进
              endIndent: 18.w, // 设置横线右边的缩进
            ),
          ),
          Column(
            children: List.generate(baseMenuList.length, (index) {
              return _settingItem(context, baseMenuList[index], spacing: 8);
            }),
          )
        ]));
  }

  Widget _settingItem(BuildContext context, MeMenuItem item,
      {int spacing = 4}) {
    String iconGoldArrow = MeAssetsConstants.getIconSettingArrow(context);
    return InkWell(
      onTap: () {
        if (item.routerMap != null && item.routerMap!.startsWith('http')) {
          CommonWebView.show(
            context,
            item.routerMap!,
          );
        } else if (item.routerMap == "language") {
          _showLanguageDialog(context);
        } else if (item.id == 111) {
          Get.to(const MeSettingPage());
        } else if (item.routerMap == "customer") {
          ImManager.jumpToCustomer();
        } else if (item.routerMap == "exit") {
          DialogManager.showLogoutDialog(context);
        } else {}
      },
      child: Padding(
        padding: EdgeInsetsDirectional.only(
            start: 15.w, top: spacing.h, bottom: spacing.h, end: 25.w),
        child: Row(children: [
          Image.network(
            item.icon ?? "",
            width: 28.w,
            height: 28.h,
            fit: BoxFit.cover,
          ),
          SizedBox(
            width: 4.w,
          ),
          (item.name ?? "").text(
              fontSize: 14.sp,
              color: const Color(0xFF000000),
              weight: TextFontWeight.regular),
          const Spacer(),
          Image.asset(
            iconGoldArrow,
            width: 20.w,
            height: 20.h,
            fit: BoxFit.cover,
          ),
        ]),
      ),
    );
  }

  // 选择本地语言
  void _showLanguageDialog(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
      ),
      builder: (BuildContext context) {
        List<Locale> firstTwoLocales =
            T.delegate.supportedLocales.take(2).toList();
        return Container(
          padding: const EdgeInsetsDirectional.all(16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: firstTwoLocales.map((locale) {
              return ListTile(
                title: Text(_getLanguageName(context, locale)),
                onTap: () async {
                  // 新增持久化存储
                  await CacheUtil.set(
                      CacheKeys.languageCode, locale.languageCode);
                  meController.updateLanguageCode(locale.languageCode);
                  await Get.updateLocale(locale);
                  Get.forceAppUpdate(); // 添加强制更新
                  Navigator.of(context).pop();
                },
              );
            }).toList(),
          ),
        );
      },
    );
  }

  // 弹框选择展示，这个可以继续优化，不然每次增加语种这里也要增加相对应代码！
  String _getLanguageName(BuildContext context, Locale locale) {
    switch (locale.languageCode) {
      // case 'en':
      //   return T.current.language_en;
      // case 'zh':
      //   return T.current.language_zh;
      // case 'ar':
      //   return T.current.language_ar;
      case 'en':
        return "English";
      case 'ar':
        return "عربي";
      default:
        return T.current.language_unknown;
    }
  }

  // hex颜色
  Color _hexToColor(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 7 || hexString.length == 9) buffer.write('FF');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  void _copyToClipboard(String textToCopy) {
    Clipboard.setData(ClipboardData(text: textToCopy));

    Fluttertoast.showToast(
      msg: T.current.me1_copied,
      toastLength: Toast.LENGTH_SHORT,
      // 显示时长 (SHORT 或 LONG)
      gravity: ToastGravity.CENTER,
      // 让 Toast 显示在屏幕中央
      backgroundColor: Colors.black54,
      textColor: Colors.white,
      fontSize: 16.0,
    );
  }
}
